define(function(require,exports,module){
	var Dialog = require("dialog");
	var aw = require("ajaxwrapper");
	
	module.exports = {
		subnav: {
			handlerSearch: function(widget){
				widget.service.search({
					s: widget.get("subnav").getValue("search"),
					properties: "productRule.product.name",
					seal:false,
					fetchProperties: widget.store.getGridFetchProperties()
				},function(ret){
					widget.get("grid").setData(ret);
				});
			},
			handleSaveBtnClick: function(widget){
				var data = {};
        		var form = widget.get("form");
        		var formData = form.getData();
        		var subGridData = widget.get("subGrid").getData();
        		var subData = $.extend(true,[],subGridData);
        		var list = [];
        		var hasOnSale = false;//用来判断必须存在一条在售的数据
        		for(var i=0;i<subData.length;i++){
        			if(subData[i].seal == false){
        				hasOnSale = true;
        			}
        			var rules = $.extend(true,[],subData[i].settlementsRules);
        			var pkRules = [];
        			for(var j=0;j<rules.length;j++){
        				pkRules.push(rules[j].pkSettlementsRule);
        			}
        			subData[i].settlementsRules = null;
        			
        			var ruleScopes = $.extend(true,[],subData[i].ruleScopes);
        			var pkScopes = [];
        			for(var k=0;k<ruleScopes.length;k++){
        				pkScopes.push(ruleScopes[k].pkScope);
        			}
        			subData[i].ruleScopes = null;
        			
        			subData[i].productType = subData[i].productType.pkProductType;
        			subData[i].productBatch = subData[i].productBatch ? 
        					subData[i].productBatch.pkProductBatch : null;
        			subData[i].unit = subData[i].unit ? subData[i].unit.key : null;
        			subData[i].productRule = null;
        			//清空多余的项
        			subData[i].bedSubsidyRuleScope = 
        				subData[i].bedSubsidyRuleScope ? subData[i].bedSubsidyRuleScope.pkScope : null;
        			subData[i].bedSubsidySettlementsRule = subData[i].bedSubsidyRuleScope ? 
        					subData[i].bedSubsidyRuleScope.pkSettlementsRule : null;
        			subData[i].couponRuleScope = subData[i].couponRuleScope ? 
        					subData[i].couponRuleScope.pkScope : null;
        			subData[i].couponSettlementsRule = subData[i].couponSettlementsRule ? 
        					subData[i].couponSettlementsRule.pkSettlementsRule : null;
        			subData[i].expenseRuleScope = subData[i].expenseRuleScope ? 
        					subData[i].expenseRuleScope.pkScope : null;
        			subData[i].expenseSettlementsRule = subData[i].expenseSettlementsRule ? 
        					subData[i].expenseSettlementsRule.pkSettlementsRule : null;

        			var l = {
    					productDetail: subData[i],
    					ruleScopes: pkScopes,
    					rules: pkRules
        			};
        			list.push(l);
        		}
        		var params = {
    				productRule: formData,
    				communityDatas: formData.communityDatas,
    				list: list,
    				pklist: widget.get("delPks")
        		}
        		if(subData.length != 0 && form.valid()){
        			if(hasOnSale){
        				Dialog.loading(true);
        				aw.ajax({
                			url: "api/productruledetail/saveall",
                			data: aw.customParam(params),
                			success: function(ret){
                				Dialog.loading(false);
                				widget.get("grid").refresh();
                				widget.set("delPks",[]);
                				widget.toList();
                			},
                			error:function(){
                				Dialog.loading(false);
                			}
                		});
        			}else{
        				Dialog.alert({
            				content:"必须存在一条在售的数据"
            			});
        			}
        		}else{
        			Dialog.alert({
        				content:"请填写子表信息"
        			});
        		}
			}
		},
		grid: {
			toEdit: function(widget,data){
				//设置主表
				var form = widget.get("form");
				form.setData(data.productRule);
				form.setReadonly("product",true);
				//根据产品查询产品类型和产品批次的下拉框
				var subForm = widget.get("subForm");
				subForm.load("productType");
				subForm.load("productBatch");
				
				//查询子表数据
				var subGrid = widget.get("subGrid");
				subGrid.loading();
				widget.service.qrySubGridData({
//					"productRule.product": data.productRule.product.pkProduct,
					"productRule.pkProductRule": data.productRule.pkProductRule,
					"orderString":"productBatch.name",
					fetchProperties: widget.store.getGridFetchProperties()
				},function(ret){
					subGrid.setData(ret);
				});
				widget.toCard();
			}
		},
		form: {
			handleProdSelChange: function(widget){
				var form = widget.get("subForm");
				form.load("productType");
				form.load("productBatch");
			}
		},
		subGrid: {
			handleAddBtnClick: function(widget){
				var form = widget.get("form");
				var product = form.getValue("product")
				if(product){
					widget.get("subForm").reset();
    				widget.toSubForm();
    				widget.set("subFormStatus","add");
				}else{
					Dialog.alert({
						content: "请先选择产品！"
					});
				}
			},
			handleEditBtnClick: function(widget,index,data){
				var subForm = widget.get("subForm");
				subForm.setData(data);
				subForm.setValue("rowIndex",index);/*用于表示当前编辑的是第几行*/
				var form = widget.get("subForm");
				var settlementsRules = data.settlementsRules || [];
				for(var i=0;i<settlementsRules.length;i++){
					subForm.setValue("settlementsRules_" + settlementsRules[i].type.key,
							settlementsRules[i].pkSettlementsRule)
				}
				var ruleScopes =data.ruleScopes || [];
				var ruleMap = {
					Expense: [],
					BedSubsidy: [],
					Coupon: []
				}
				for(var j=0;j<ruleScopes.length;j++){
					ruleMap[ruleScopes[j].ruleType.key].push(ruleScopes[j].pkScope);
				}
				for(var k in ruleMap){
					subForm.setValue("ruleScope_" + k,ruleMap[k]);
				}
				widget.set("subFormStatus","edit");
				widget.toSubForm();
			},
			handleDelBtnClick: function(widget,index,data){
				//证明删除的是一条已经存在在数据库中的数据
				Dialog.confirm({
					content: "删除的数据将无法恢复，是否确认删除？",
					confirm: function(){
						if(data.pkProductRuleDetail){
							widget.get("delPks").push(data.pkProductRuleDetail);
						}
						Dialog.close();
						widget.get("subGrid").remove(index);
					}
				});
			},
			handleChgBtnClick: function(widget,index,data){
				var subGrid = widget.get("subGrid");
				var datas = subGrid.getData();
				var length = datas.length;
				for(var i=0;i<length;i++){
					if(i !== index){
						//不和自己比
						if(datas[i].seal == true){
							continue;
						}else if(datas[i].productType.pkProductType == data.productType.pkProductType){
							if(datas[i].productBatch == null && data.productBatch == null){
								datas[i].seal = !datas[i].seal;
							}else if(datas[i].productBatch != null && data.productBatch != null && 
									datas[i].productBatch.pkProductBatch == data.productBatch.pkProductBatch){
								datas[i].seal = !datas[i].seal;
							}else{
								continue;
							}
						}else{
							continue;
						}
					}
				}
				data.seal = !data.seal;
				widget.get("subGrid").setData(datas);
			}
		},
		subForm: {
			handleSaveBtnClick: function(widget){
				var form = widget.get("form");
				var subForm = widget.get("subForm");
				var subGrid = widget.get("subGrid");
				var subGridData = subGrid.getData();
				var rowIndex = subForm.getValue("rowIndex");
				var subFormData = subForm.getData();
				//校验重复
				//1首先校验已保存的数据中是否含有相同的（产品名称+产品类型+产品批次）的数据
				widget.service.queryOnly({
					"productRule.product.name": form.getPlugin("product").getText(),
					"productType.name":subForm.getPlugin("productType").getText(),
					"productBatch.name":subForm.getPlugin("productBatch").getText(),
				},function(data){
					if(data.length == 0){
						//再次校验前台已经填写的数据
						var isValid = true;
						for(var i =0;i<subGridData.length;i++){
							console.log(subGridData[i]);
							if(subGridData[i].productType.pkProductType == subForm.getValue("productType")){
								if(!subGridData[i].productBatch && !subForm.getValue("productBatch")){
									isValid = false;
								}else if(subGridData[i].productBatch  && subForm.getValue("productBatch") && 
										subGridData[i].productBatch.pkProductBatch == subForm.getValue("productBatch")){
									isValid = false;
								}else{
									continue;
								}
							}
						}
						if(!isValid){
							Dialog.alert({
								content: "产品名称+产品类型+产品批次重复"
							})
							return false;
						}
						var procData = widget.store.procSubFormData(
							subFormData,
		        			subForm.getData("productType"),
		        			subForm.getData("productBatch"),
		        			subForm.getData("unit"),
		        			subForm.getData("settlementsRules_Expense"),
		        			subForm.getData("ruleScope_Expense"),
		        			subForm.getData("settlementsRules_BedSubsidy"),
		        			subForm.getData("ruleScope_BedSubsidy"),
		        			subForm.getData("settlementsRules_Coupon"),
		        			subForm.getData("ruleScope_Coupon")
						);
						if(rowIndex){
							//修改一行
							procData.pkProductRuleDetail = subFormData.pkProductRuleDetail;
							procData.version = subFormData.version;
							subGrid.update(rowIndex,procData);
						}else{
							//新增一行
							var subGrid = widget.get("subGrid");
			            	var oldData = subGrid.getData();
			            	oldData.push(procData);
			            	subGrid.setData(oldData);
						}
		            	widget.toCard();
					}else{
						Dialog.alert({
							content: "产品名称+产品类型+产品批次重复"
						});
					}
				});
			}
		}
	};
})
